package hips.images.integer.gray8;

import hips.Image;
import hips.images.integer.ImageInt;
import ij.ImagePlus;

public class ImageGray8 extends ImageInt<PixelValueGray8> {

	private byte pixels[][];

	public ImageGray8(ImagePlus impl) {
		height = impl.getHeight();
		width = impl.getWidth();
		size = height * width;
		slices = impl.getStackSize();
		channels = 1;
		pixels = new byte[slices][];
		for (int i = 0; i < slices; i++) {
			pixels[i] = (byte[]) impl.getStack().getProcessor(i + 1).getPixels();
		}
		initialize(impl);
	}

	public ImageGray8(ImageGray8 img) {
		height = img.getHeight();
		width = img.getWidth();
		size = height * width;
		slices = img.getSlices();
		channels = 1;
		ImagePlus impl = img.getImagePlus().createImagePlus();
		impl.setTitle("Created from:  " + img.getTitle());
		ij.ImageStack stack = new ij.ImageStack(width, height);
		for (int i = 0; i < img.getSlices(); i++) {
			stack.addSlice("" + i, img.getImagePlus().getStack().getProcessor(i + 1).createProcessor(width, height));
		}
		impl.setStack(stack);
		pixels = new byte[slices][];
		for (int i = 0; i < slices; i++) {
			pixels[i] = (byte[]) impl.getStack().getProcessor(i + 1).getPixels();
		}
		initialize(impl);
	}

	public PixelValueGray8 getPixelValue(int index) {
		PixelValueGray8 p = new PixelValueGray8(slices);
		for (int i = 0; i < slices; i++) {
			p.setValueInt(0x0FF & pixels[i][index], i);
		}
		return p;
	}

	public PixelValueGray8 getPixelValue(PixelValueGray8 pvalue, int index) {
		for (int i = 0; i < slices; i++) {
			pvalue.setValueInt(0x0FF & pixels[i][index], i);
		}
		return pvalue;
	}

	public PixelValueGray8 newPixelValue(int value) {
		PixelValueGray8 p = new PixelValueGray8(slices);
		for (int i = 0; i < slices; i++) {
			p.setValueInt(value, i);
		}
		return p;
	}

	public PixelValueGray8 newPixelValue() {
		PixelValueGray8 p = new PixelValueGray8(slices);
		for (int i = 0; i < slices; i++) {
			p.setValueInt(0, i);
		}
		return p;
	}

	public Image<PixelValueGray8> newImage() {
		return new ImageGray8(this);
	}

	public PixelValueGray8 newPixelValue(Number value) {
		return newPixelValue(value.intValue());
	}

	public void putPixelValue(int index, PixelValueGray8 pixel) {
		for (int i = 0; i < slices; i++) {
			pixels[i][index] = (byte) pixel.getValueInt(i);
		}
	}

}
